package com.lening.gateway.filter;


import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import com.lening.gateway.utils.IPutil;
import com.lening.gateway.web.Request;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cloud.client.loadbalancer.Response;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.util.HashMap;

@Slf4j
public class LogFilter implements GlobalFilter, Ordered {



    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        String uri = exchange.getRequest().getURI().toString();
        if (uri.contains("log/log/page")) {
            return chain.filter(exchange);
        }
        log.info("日志过滤器LogFilter");
        ServerHttpRequest request = exchange.getRequest();
        String token = exchange.getRequest().getHeaders().getFirst("token");

        //LoginUser user = JwtUtil.getCurrentUser("eyJhbGciOiJIUzM4NCIsInR5cCI6IkpXVCJ9.eyJ1c2VySWQiOjEsInVzZXJuYW1lIjoiYWRtaW4ifQ.fy2Es_m9n9fHFjHTDxUT8F05glQqjnZPhMQM6dgYtMlx-e_PYvkRmMZkOoutHGjm");
        HttpHeaders requestHeaders = request.getHeaders();
//        URI uri = request.getURI();
        HashMap<Object, Object> map = new HashMap<>();
        String platform = requestHeaders.getFirst("sec-ch-ua-platform");
        //map.put("username", user.getUsername());
        map.put("platform",platform);
        String ip = IPutil.getIpAddress(request);
//        map.put("",request.getLocalAddress().toString());
        map.put("username", "admin");
//        map.put("requestPath",request.getPath());
        map.put("requestMethod",request.getMethod());
        map.put("uri",request.getURI());
        map.put("requestBody",request.getQueryParams().toString());
//        map.put("requestBody",request.getBody());
//        map.put("responseData", Response.class);
        map.put("ip",ip);
//        map.put("targetServer",request.getQueryParams());

        Request.asyncPosts("community-log/log/addLog", map, String.class).subscribe(
                result -> {
                    // 处理返回的结果
                    System.out.println("Response: " + result);
                },
                error -> {
                    // 处理错误情况
                    error.printStackTrace();
                }
        );
        //把当前的交换交给过滤器链
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return -3;
    }
}
